﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using FrameWork.Util.Http;
using MyDb.DoMain.DbContext;
using MyDb.DoMain.Entity.DbEntity;
using MyDb.DoMain.Entity.SelfModel.Account;
using MyDb.DoMain.Entity.ViewModel.Account.Auth;
using MyDb.DoMain.Interface;

namespace MyDb.DoMain.Service
{
    public class UserService : IUserService
    {
        /// <summary>
        /// 获取全部的用户列表
        /// </summary>
        public List<T_User> GetAllUserList()
        {
            using (var dbContext = new MyDbContext())
            {
                var userList = dbContext.Users.ToList();
                return userList;
            }
        }

        public void UpdateUser()
        {
            using (var dbContext = new MyDbContext())
            {
                var t = dbContext.Users.FirstOrDefault(u => u.Id > 0);
                t.Email = "ddddddddd@qqq.com";
                dbContext.Update(t);
            }
        }

        /// <summary>
        /// 登录方法
        /// </summary>
        public LoginModel Login(LoginSaveModel loginSaveModel)
        {
            using (var dbContext = new MyDbContext())
            {
                LoginModel viewModel = null;
                var model = dbContext.Users.Where(u => u.Account == loginSaveModel.UserName
                        && u.Password == loginSaveModel.Password && !u.IsDel && u.IsUsed).Include(u=>u.UserRoles).FirstOrDefault();
                if (model != null)
                {
                    var log = new T_LoginLog
                    {
                        CreateTime = DateTime.Now,
                        LoginToken = Guid.NewGuid().ToString(),
                        UserId = model.Id,
                        UserName = model.Account,
                        ClientIP = Fetch.UserIp
                    };
                    dbContext.Insert(log);
                    viewModel = new LoginModel
                    {
                        Account = model.Account,
                        Age = model.Age,
                        Sex = model.Sex,
                        Email = model.Email,
                        Phone = model.Phone,
                        RealName = model.RealName,
                        UserId = model.Id,
                        LoginToken = log.LoginToken,
                        HeadImg = model.HeadImg,
                        LoginTime = log.CreateTime,
                        RoleIdsStr = string.Join(",", model.UserRoles)
                    };
                }
                return viewModel;
            }
        }
    }
}
